<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function convertListToTree(list) {
        const map = {}; // 使用一个对象来存储每个节点的引用
        // 遍历列表并将每个节点存储在 map 中
        list.forEach(item => {
          map[item.id] = { ...item, children: [] };
        });
        // 遍历列表构建树形结构
        const tree = [];
        list.forEach(item => {
          if (item.pid !== 0) {
            map[item.pid].children.push(map[item.id]);
          } else {
            tree.push(map[item.id]);
          }
        });
        return tree;
      }

      const list = [
        {
          id: 1,
          name: 'jack',
          pid: 0
        },
        {
          id: 9,
          name: 'jack',
          pid: 0
        },
        {
          id: 2,
          name: 'jack',
          pid: 1
        },
        {
          id: 3,
          name: 'jack',
          pid: 2
        },
        {
          id: 4,
          name: 'jack',
          pid: 3
        }
      ];

      const tree = convertListToTree(list);
      console.log(tree);

    </script>
  </body>
</html>
